var mysql = require('mysql')
// var async = require('async'); 
var log = require("./../../util/loginfo").getInstand;
var mysql_config=require("../../util/mysql_config");
const { now } = require('lodash');

var pool = mysql.createPool({
	connectionLimit:10000,
	host:mysql_config.host,
	user:mysql_config.user,
	password:mysql_config.password,
	port:mysql_config.port,
	database:'ym_manage'
})

//获取某代理的上级代理记录 所有上级
exports.getAgentLevelById = function getAgentLevelById(uid, callback){

	var sql = "SELECT aid FROM uidglaid WHERE uid = " + uid
	+ " union all (select aid from uidglaid where uid = (SELECT aid FROM uidglaid WHERE uid = " + uid 
	+ " )) union all (select aid from uidglaid where uid = (SELECT aid FROM uidglaid WHERE uid = ( SELECT aid FROM uidglaid WHERE uid = " + uid + ")))";

	pool.getConnection(function(err,connection){
		connection.query({sql:sql},function(err,rows){
			connection.release();
			if (err)
			{
				log.err("uidglaid");
				log.err(err);
				callback(-1);
			}else{
				if (rows[0]){
					log.info(11111111);
					callback(1,rows);
				}else{
					callback(0);
				}
			}})
	});
}

exports.getBackFeeRecord = function getBackFeeRecord(uid, callback){
	var sql = "SELECT * FROM recharge_back_fee WHERE aid = ? ORDER BY id DESC limit 1";
	var values = [];
	values.push(uid);

	log.info("getBackFeeRecord begin");
	pool.getConnection(function(err,connection){
		connection.query({sql:sql,values:values},function(err,rows){
			if (err)
			{
				log.err("getBackFeeRecord");
				log.err(err);
				callback(0);
			}else{
				if (rows[0]){
					callback(1,rows);
				}else{
					callback(1);
				}
			}
			connection.release();
		})
	});
}

exports.saveBackFeeRecord = function saveBackFeeRecord(uid, aid, betCoin, originFee, addFee, currentFee, callback){
	var sql = "INSERT INTO recharge_back_fee (uid, aid, bet_coin, origin_fee, add_fee, current_fee) VALUES (?,?,?,?,?,?)";
	var values = [];
	values.push(uid);
	values.push(aid);
	values.push(betCoin);
	values.push(originFee);
	values.push(addFee);
	values.push(currentFee);

	log.info("saveBackFeeRecord begin");
	pool.getConnection(function(err,connection){
		connection.query({sql:sql,values:values},function(err,rows){
			connection.release();
			if (err)
			{
				log.err("saveBackFeeRecord");
				log.err(err);
				callback(0);
			}else{
				callback(1, rows.insertId);
			}})
	});
	log.info("saveBackFeeRecord end");
}

exports.getMyBackFeeRecord = function getMyBackFeeRecord(sql, callback){

	log.info("getMyBackFeeRecord begin");
	pool.getConnection(function(err,connection){
		connection.query({sql:sql},function(err,rows){
			connection.release();
			if (err)
			{
				log.err("getMyBackFeeRecord");
				log.err(err);
				callback(0);
			}else{
				callback(1, rows);
			}})
	});
	log.info("getMyBackFeeRecord end");
}



